package test.my.com.myapplicationtest.recycleview_expand;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import test.my.com.myapplicationtest.R;

/**
 * Author : Cooper
 * Time : 2017/5/9  10:15
 * Description : 扩展列表RecycleView （上拉加载）
 */

public class ExpandRecycleViewOld extends RecyclerView {

    private Context mContext;
    private LinearLayoutManager mLinearLayoutManager;
    private PullUpListener mPullUpListener;
    private ExpandRecycleViewAdapter mExpandRecycleViewAdapter;
    private RefreshHeaderView mRefreshHeaderView;

    public void setPullUpListener(PullUpListener pullUpListener) {
        this.mPullUpListener = pullUpListener;
    }

    public ExpandRecycleViewOld(Context context) {
        super(context);
        init(context);
    }

    public ExpandRecycleViewOld(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ExpandRecycleViewOld(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        this.mContext = context;
        mLinearLayoutManager = new LinearLayoutManager(context);
        this.setLayoutManager(mLinearLayoutManager);
        this.setHasFixedSize(true);
        this.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLinearLayoutManager) {
            @Override
            public void pullUp() {
                if (mPullUpListener != null && mExpandRecycleViewAdapter.mBottomStatus != ExpandRecycleViewAdapter.STATUS_LOAD_OVER && !mExpandRecycleViewAdapter.isPullDown) {
                    mPullUpListener.loadMore();
                }
            }
        });
    }

    /**
     * 添加扩展adapter
     * @param expandAdapter
     */
    public void setExpandAdapter(ExpandRecycleViewAdapter expandAdapter) {
        this.mExpandRecycleViewAdapter = expandAdapter;
        this.setAdapter(expandAdapter);
    }

    /**
     * 判断滑动到底部的监听
     */
    public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
        /**
         * 最后一个的位置
         */
        private int[] lastPositions;

        /**
         * 最后一个可见的item的位置
         */
        private int lastVisibleItemPosition;

        /**
         * 当前滑动的状态
         */
        private int currentScrollState = 0;

        private LinearLayoutManager mLLManager;

        public EndlessRecyclerOnScrollListener(
                LinearLayoutManager linearLayoutManager) {
            this.mLLManager = linearLayoutManager;
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            currentScrollState = newState;
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            int visibleItemCount = layoutManager.getChildCount();
            int totalItemCount = layoutManager.getItemCount();
            if ((visibleItemCount > 0 && currentScrollState == RecyclerView.SCROLL_STATE_IDLE && (lastVisibleItemPosition) >= totalItemCount - 1)) {
                pullUp();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItemPosition = mLLManager.findLastVisibleItemPosition();
        }

        public abstract void pullUp();
    }

    public abstract static class ExpandRecycleViewAdapter<T> extends RecyclerView.Adapter {

        public static final int TYPE_BOTTOM = 0x001; // 底部item
        public static final int TYPE_NORMAL = 0x002; // 正常业务item

        public static final int STATUS_LOADING = 0x003; // 正在加载
        public static final int STATUS_LOAD_COMPLETEED = 0x004; // 加载完毕
        public static final int STATUS_LOAD_OVER = 0x005; // 已经到底了
        public static final int STATUS_NORMAL = 0x006; // 正常状态

        public int mBottomStatus = STATUS_NORMAL;
        public boolean isPullDown;// 是否处于下拉刷新状态

        private List<T> mList;
        private Context mContext;

        public ExpandRecycleViewAdapter(List<T> mList, Context mContext) {
            this.mList = mList;
            this.mContext = mContext;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_BOTTOM) {
                return new BottomViewHolder(createBottomView());
            } else if (viewType == TYPE_NORMAL) {
                return createNormalViewHolder(parent);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof BottomViewHolder) {
                BottomViewHolder bottomViewHolder = (BottomViewHolder) holder;
                switch (mBottomStatus) {
                    case STATUS_NORMAL:
                        bottomViewHolder.textView.setText("");
                        break;
                    case STATUS_LOADING:
                        bottomViewHolder.textView.setText("加载中...");
                        break;
                    case STATUS_LOAD_COMPLETEED:
                        bottomViewHolder.textView.setText("加载数据完毕");
                        break;
                    case STATUS_LOAD_OVER:
                        bottomViewHolder.textView.setText("已经到底了");
                        break;
                }
            } else {
                bindNormalViewHolder(holder, position);
            }
        }

        @Override
        public int getItemCount() {
            return mList.size() + 1;
        }

        @Override
        public int getItemViewType(int position) {
            if (position+1  == getItemCount()) {
                return TYPE_BOTTOM;
            } else {
                return TYPE_NORMAL;
            }
        }

        public void setBottomViewType(int status) {
            this.mBottomStatus = status;
            this.notifyDataSetChanged();
        }

        /**
         * 创建业务逻辑viewholder
         * @return
         */
        public abstract RecyclerView.ViewHolder createNormalViewHolder(ViewGroup parent);

        /**
         * 绑定业务逻辑到viewholder
         * @param holder
         * @param position
         */
        public abstract void bindNormalViewHolder(RecyclerView.ViewHolder holder, int position);

        /**
         * 创建底部加载view
         * @return
         */
        public RelativeLayout createBottomView() {
            RelativeLayout relativeLayout = new RelativeLayout(mContext);
            relativeLayout.setTag(2);
            relativeLayout.setBackgroundColor(ContextCompat.getColor(mContext, R.color.grey));
            TextView textView = new TextView(mContext);
            textView.setTag(1);
            textView.setTextColor(ContextCompat.getColor(mContext, R.color.grey));
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            relativeLayout.addView(textView, layoutParams);
            relativeLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50));
            return relativeLayout;
        }
    }

    /**
     * 底部加载ViewHolder
     */
    static class BottomViewHolder extends RecyclerView.ViewHolder {

        public TextView textView;
        public RelativeLayout relativeLayout;

        public BottomViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewWithTag(1);
            relativeLayout = (RelativeLayout) itemView.findViewWithTag(2);
        }
    }

    /**
     * 上拉加载 回调接口
     */
    public interface PullUpListener {
        void loadMore();
    }

    /**
     * item点击事件 回调接口
     */
    public interface ItemClickListener {
        void itemClick(int position);
    }


}

